#include <iostream>
using namespace std;

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <fstream>
#include <cstring>
#include <sys/wait.h>



#define FIFONAME "./testFifo"

int main()
{
    if(access(FIFONAME,F_OK) == -1)
    {
        int ret =  mkfifo(FIFONAME,0644);
        if(ret == -1)
        {
            perror("mkfifo error");
            exit(1);
        }
    }

    /* 创建进程 */
    pid_t pid =fork();
    if(pid < 0)
    {
        perror("fork error!");
        exit(1);
    }
    else if(pid == 0)
    {
        /* 子进程 */
        int readFd = open(FIFONAME,O_RDONLY);
        if(readFd == -1)
        {
            perror("open fifo error");
            exit(1);
        }

    
        char buffer[128] = { 0 };
        int readBytes = 0;

        while(1)
        {
            /* 清空脏数据 */
            memset(buffer,0,sizeof(buffer));

            readBytes =  read(readFd,buffer,sizeof(buffer) - 1);
            if(readBytes < 0)
            {
                perror("read error!");
                exit(1);
            }
            if(readBytes == 0)
            {
                break;
            }
            printf("buf = %s\n",buffer);
            sleep(1);
            
        }

    }
    else
    {
        /* 父进程 */
        int writeFd = open(FIFONAME,O_WRONLY);
        if(writeFd == -1)
        {
            perror("open fifo error");
            exit(1);
        }

        ifstream ifs;
        /* 打开文件 */
        ifs.open("lyric.txt",ios::in | ios::out);
        if(ifs.is_open() == false)
        {
            perror("ifs open error!");
            exit(1);
        }

        char buffer[128] = { 0 };


        // int fd = open("lyric.text",O_RDONLY);
        // if(fd == -1)
        // {
        //     perror("open lyric.txt error");
        //     exit(1);
        // }
        
        int writeBytes = 0;
        while(ifs.eof() == false)
        {
            ifs.getline(buffer,sizeof(buffer));

            //printf("%s\n",buffer);

            writeBytes =  write(writeFd,buffer,strlen(buffer));
            if(writeBytes == 0)
            {
                break;
            }
            /* 清空脏数据 */
            memset(buffer,0,sizeof(buffer));

            sleep(1);
            
        }

        /* 关闭文件 */
        ifs.close();

        wait(NULL);
    }

    return 0;
}